import router from '@/router'
import { loginAPI, adminMessage } from '@/api/user'
import { setLocalStorage, getLocalStorage, delLocalStorage } from '@/utils/storage'
export default {
  namespaced: true,
  state () {
    return {
      token: getLocalStorage('token') || ''
    }
  },
  getters: {},
  mutations: {
    setToken (state, payload) {
      setLocalStorage('token', payload)
      state.token = payload
    },
    delToken (state) {
      if (getLocalStorage('token')) {
        delLocalStorage('token')
        state.token = ''
      }
    }
  },
  actions: {
    // 管理员登录
    async adminLogin (context, payload) {
      try {
        const result = await loginAPI(payload)
        context.commit('setToken', result.data.data.token)
        return result
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 管理员信息
    updateAdminMessage (context) {
      return adminMessage()
        .then((res) => {
          const token = res.config.headers.Authorization
          const newToken = token.split(' ')[1]
          context.commit('setToken', newToken)
          return res
        })
        .catch((error) => {
          router.push({ path: '/login' })
          return Promise.reject(error)
        })
    }
  }
}
